const { search } = require("../../template/table/table_tpl");


//导出
module.exports = {
  tableMethods: tableMethods,
  tableDefaultMounted: tableDefaultMounted, //mounted的table部分
  tableDefaultMethods: tableDefaultMethods, //默认函数，需要二次传参进去
};



function tableMethods(tableOpt, tableConfig, module_config) {

  var methodsCodeFirst = "";
  var methodsCodeSecond = "";

  //额外的请求
  var extraMethodsObj = getExtraRequestObj(tableConfig);
  var {
    firstExtraMethods,
    secondExtraMethods
  } = extraMethodsObj;
  methodsCodeFirst += firstExtraMethods;
  methodsCodeSecond += secondExtraMethods;
  tableOpt.forEach((item, index) => {
    if (item.type == 'view') {
      methodsCodeFirst += handleViewFirst({ text: item.text });
      methodsCodeSecond += handleViewSecond({
        path: item.jump,
        text: item.text,
        extraQueryParams: item.extraQueryParams
      });
      // console.log(methodsCodeFirst);
      // console.log(methodsCodeSecond);
    } else if (item.type == 'modify') {
      methodsCodeFirst += handleModifyFirst({ text: item.text });
      methodsCodeSecond += handleModifySecond({ 
        path: item.jump, 
        text: item.text,
        extraQueryParams: item.extraQueryParams,
      });
      // console.log(methodsCodeFirst);
      // console.log(methodsCodeSecond);
    } else if (item.type == 'del') {
      methodsCodeFirst += handleDeleteFirst({ text: item.text });
      methodsCodeSecond += handleDeleteSecond({
        url: item.url,
        data: item.params,
        requestType: item.requestType, //
        text: item.text,
        isSplitSearchString: item.isSplitSearchString,
      });
      // console.log(methodsCodeFirst);
      // console.log(methodsCodeSecond);
    } else if (item.type == 'changeState') {
      methodsCodeFirst += handleChangeStateFirst({
        text: item.text, //注释
        methodNameTag: item.methodNameTag, //方法拓展
      });
      methodsCodeSecond += handleChangeStateSecond({
        url: item.url,
        data: item.params,
        requestType: item.requestType, //
        text: item.text,
        methodNameTag: item.methodNameTag, //方法衔接拓展名
      });
    } else if (item.type == "sort") {
      methodsCodeFirst += handleSortFirst ();
      methodsCodeSecond += handleSortSecond ({
        url: item.url,
        requestType: item.requestType, //请求方式
        //备注，打开排序，排序
      });
    }
  });

  //返回方法集合，有两个
  return {
    tableMethodsFirst: methodsCodeFirst,
    tableMethodsSecond: methodsCodeSecond,
  };
};


//额外方法添加
function getExtraRequestObj(tableConfig) {
  var firstExtraMethods = "";
  var secondExtraMethods = "";
  //data
  //mounted
  //methods 拆分成两个部分
  for (var itemKey in tableConfig.extraRequest) {
    if (itemKey == 'methodsCode') {
      var extraItem = tableConfig.extraRequest['methodsCode'];
      extraItem.forEach((item, index) => {
        if (item.type.includes("opts")) {
          firstExtraMethods += `
            //${item.explainText}
            ${item.methodName} () {
              this.allMethods.${item.methodName}();
            },
            `;
          //用于列表展示的枚举
          var showCodeStr = ``;
          if (item.showConfig) {
            showCodeStr += `
                //用列表展示的字段
                var shows = {};
                res.data.records.forEach((item, index)=> {
                  shows[item.${item.showConfig.key} + ''] = item['${item.showConfig.value}'];
                })
                _this.${item.showName} = shows;
                console.log(_this.${item.showName})
              `;
          }
          secondExtraMethods += `
            //${item.explainText}
            ${item.methodName} () {
              var url = ${item.api};
              var data =${item.params};
              console.log("参数", data);
              jhTools.post(
                url,
                data,
                null,
                (res) => {
                  console.log("结果", res);
                  if (res.code == 200) {
                    var opts = [];
                    res.data.records.forEach((item, index) => {
                      opts.push({
                        label: item.${item.optsConfig.label},
                        value: item.${item.optsConfig.value}
                      })
                    });
                    _this.${item.optsName} = opts;
                    ${showCodeStr}
                  } else {
                    _this.$message({
                      type: "warning",
                      message: res.message,
                    });
                  }
                },
                (err) => {
                  console.log(err);
                }
              );
            },
            `;
        }
      })
    }
  }
  return {
    firstExtraMethods,
    secondExtraMethods
  }
}



//查看
function handleViewFirst(opt) {
  var text = opt.text ? opt.text : '查看';
  return `
      //${text}
      handleView (e) {
        this.allMethods.handleView(e);
      },
    `;
}

function handleViewSecond(opt) {
  if (!opt) throw new Error('生成查看函数请传参opt')
  var path = opt.path;
  var text = opt.text ? opt.text : '查看';
  var query = opt.extraQueryParams ? opt.extraQueryParams : "{ id }";
  if (!path) throw new Error('生成查看函数请传参path');
  return `
    //${text}
    handleView (e) {
      var { id } = e.currentTarget.dataset;
      _this.$router.push({
        path: '${path}',
        query: ${query}
      });
    },
  `;
}

//编辑/修改
function handleModifyFirst(opt) {
  var text = opt.text ? opt.text : '修改';
  return `
    //${text}
    handleModify (e) {
      this.allMethods.handleModify(e);
    },
  `;
}

function handleModifySecond(opt) {
  if (!opt) throw new Error('生成修改函数请传参opt')
  var path = opt.path;
  var text = opt.text ? opt.text : '修改',
  extraQueryParams = opt.extraQueryParams ? opt.extraQueryParams : "{ id }";
  if (!path) throw new Error('生成修改函数请传参path');
  return `
    //${text}
    handleModify (e) {
      var { id } = e.currentTarget.dataset;
      _this.$router.push({
        path: '${path}',
        query: ${extraQueryParams}
      });
    },
  `;
}

//删除
function handleDeleteFirst(opt) {
  var text = opt.text ? opt.text : '删除';
  return `
    //${text}
    handleDelete (e) {
      this.allMethods.handleDelete(e);
    },
  `;
}

function handleDeleteSecond(opt) {
  var url = opt.url, //API.task_manager.aifencang_check
    data = opt.data ? opt.data : `{ id }`, //必须携带id, 且为字符串
    requestType = opt.requestType ? opt.requestType : 'post',  //请求类型
    isSplitSearchString = opt.isSplitSearchString ? opt.isSplitSearchString : "";
  if (isSplitSearchString == 'true') {
    url = url + ` + "?id=" + id`
  }
  var text = opt.text ? opt.text : '删除';
  return `
  //${text}
  handleDelete(e) {
    const { id } = e.currentTarget.dataset;
    var url = ${url};
    var data = ${data};
    console.log("参数", data);
    _this.$confirm("是否确认删除？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
          ${requestType == 'post' ? `
          jhTools.post(
            url,
            data,
            null,
          ` : `
          jhTools.get(
            url,
            null,
            data,
          `}
            (res) => {
              console.log("结果", res);
              if (res.code == 200) {
                _this.$message({
                  type: "success",
                  message: "操作成功",
                });
                _this.getInitData();
              } else {
                _this.$message({
                  type: "warning",
                  message: res.message,
                });
              }
            },
            (err) => {
              console.log(err);
            }
          );

      })
      .catch(() => {
        this.$message({
          type: "info",
          message: "已取消",
        });
      });

  },
  `;
}

//改变状态
function handleChangeStateFirst(opt) {
  var text = opt.text ? opt.text : '改变状态',
    methodNameTag = opt.methodNameTag ? opt.methodNameTag : '';
  return `
    //${text}
    handleChangeState${methodNameTag} (e) {
      this.allMethods.handleChangeState${methodNameTag} (e);
    },
  `;
}

function handleChangeStateSecond(opt) {
  var url = opt.url, //API.task_manager.aifencang_check
    data = opt.data ? opt.data : `{ id }`, //必须携带id, 且为字符串
    requestType = opt.requestType ? opt.requestType : 'post',  //请求类型
    text = opt.text ? opt.text : '改变状态',
    methodNameTag = opt.methodNameTag ? opt.methodNameTag : '';
  return `
    //${text}
    handleChangeState${methodNameTag} (e) {
      const { id } = e.currentTarget.dataset;
      var url = ${url};
      var data = ${data};
      console.log("参数", data);
      ${requestType == 'post' ? `
      jhTools.post(
        url,
        data,
        null,
      ` : `
      jhTools.get(
        url,
        null,
        data,
      `}
        (res) => {
          console.log("结果", res);
          if (res.code == 200) {
            _this.$message({
              type: "success",
              message: "操作成功",
            });
            _this.getInitData();
          } else {
            _this.$message({
              type: "warning",
              message: res.message,
            });
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    `;
}


//排序按钮
function handleSortFirst () {
  return `
    //打开排序
    handleOpenBtnWrap (e) {
      this.allMethods.handleOpenBtnWrap(e);
    },

    //排序
    handleSort (e) {
      this.allMethods.handleSort(e);
    },
  `;
}

function handleSortSecond (opt) {
  var { url, requestType } = opt;
  requestType = requestType ? requestType : 'post';
  //保存参数sortIndex
  return `
  //打开排序
  handleOpenBtnWrap(e) {
    const id = e.currentTarget.dataset.id;
    $(".sortWrap" + id).removeClass("hidden");
    $(".openSort" + id).addClass("hidden");
  },

  //排序
  handleSort(e) {
    var id = e.currentTarget.dataset.id;
    var url = ${url};
    var data = {
      id,
      sort: Number(_this.sortIndex),
    };
    console.log("参数", data);
    ${requestType == 'post' ? `
    jhTools.post(
      url,
      data,
      null,
    ` : `
    jhTools.get(
      url,
      null,
      data,
    `}
      (res) => {
        console.log("结果", res);
        if (res.code == 200) {
          _this.$message({
            type: "success",
            message: "操作成功"
          })
        }
      },
      (err) => {
        console.log(err);
      }
    );

    $(".openSort" + id).removeClass("hidden");
    $(".sortWrap" + id).addClass("hidden");
  },
  `
}


//挂载默认函数
function tableDefaultMounted(tableConfig) {
  var extraMountedStr = ``;
  for (var itemKey in tableConfig.extraRequest) {
    var extraItem = tableConfig.extraRequest[itemKey];
    if (itemKey == 'methodsCode') {
      extraItem.forEach((item, index) => {
        if (item.type.includes("opts")) {
          extraMountedStr += `
            this.${item.methodName}(); //${item.explainText}
          `;
        }
      })
    }
  }
  var totalMountedStr = `
    this.initRequest();
    ${extraMountedStr}
    this.getInitData();
  `;
  return totalMountedStr;
}

//table方法集合
function tableDefaultMethods(module_config, tableConfig) {
  //传入module_config 获取module_name拼接pageSearch字段
  var module_name = "";
  for (var item in module_config) {
    if (item == 'module_name') {
      module_name = module_config[item];
    }
  }

  // pageSearch: 
  var pageSearch = "",
    searchUrl = "";
  if (tableConfig.pageApi) {
    pageSearch = tableConfig.pageApi;
    searchUrl = pageSearch;
  } else {
    pageSearch = `API.${module_config.module_name}.page`;
    searchUrl = pageSearch;
  }

  var { extraPageRequestParams } = tableConfig;
  if (!extraPageRequestParams) extraPageRequestParams = "";

  return `
    //表格默认函数
    //初始化
    initRequest() {
      this.LingChuang_request = jhTools.LingChuang_request({
        this: this,
        pageUrl: ${pageSearch},
        searchUrl: ${searchUrl},
        searchData: {},
      });
      // console.log(this.LingChuang_request);
    },
    //加载数据
    getInitData: function () {
      var _this = this;
      this.LingChuang_request.getInitData(
        {
          pageIndex: this.currentPageIdx,
          pageSize: this.onePageSize,
          ${extraPageRequestParams}
        },
        function (res) {
          //初始格式化数据
        }
      );
    },
    //格式化数据
    formatData() {
      this.LingChuang_request.formatData();
    },
    //格式化页面
    formatPaging(res) {
      this.LingChuang_request.formatPaging(res);
    },
    //页数跳转
    handleSizeChange(val) {
      this.LingChuang_request.handleSizeChange(val);
    },
    //页面点击跳转
    handleCurrentChange(val) {
      this.LingChuang_request.handleCurrentChange(val);
    },
    //enter跳转
    handleEnter() {
      this.LingChuang_request.getPagingData(
        this.currentPageIdx,
        this.onePageSize
      );
    },
    //分页数据
    getPagingData(pageIndex, pageSize) {
      this.LingChuang_request.handleEnter(pageIndex, pageSize);
    },
    //列表勾选1
    toggleSelection(rows) {
      this.LingChuang_request.toggleSelection(rows);
    },
    //列表勾选2
    handleSelectionChange(val) {
      this.LingChuang_request.handleSelectionChange(val);
    },
    //表格默认函数
  `;
}